/**
 * @Title: UserUpdatePasswordFragment.java
 * @author: Abtswiath丶lxy
 * @data: 2016年6月15日 上午11:08:23 <创建时间>
 * @history：<以下是历史记录>
 * @modifier: <修改人>
 * @modify date: 2016年6月15日 上午11:08:23 <修改时间>
 * @log: <修改内容>
 * @modifier: <修改人>
 * @modify date: 2016年6月15日 上午11:08:23 <修改时间>
 * @log: <修改内容>
 */
package com.sunmi.usercenter.ui.activity.fragment;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.Shop;
import com.sunmi.usercenter.bean.rpc.ReqUpdatePassword;
import com.sunmi.usercenter.bean.rpc.ReqVerifyPassword;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import com.sunmi.usercenter.utils.MD5Utils;
import com.sunmi.usercenter.utils.NetWorkCenterUtils;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import sunmi.sunmiui.dialog.DialogCreater;
import sunmi.sunmiui.dialog.EditPwdDialog;

/**
 * TODO<请描述这个类是干什么的>
 *
 * @author Abtswiath丶lxy
 * @versionCode 1 <每次修改提交前+1>
 */
public class UserUpdatePasswordFragment extends SuperFragment implements OnClickListener {

    private View mView;
    private RelativeLayout mRelBack, mRelClearOld, mRelClearNew;
    private EditText mEditOldPsd, mEditNewPsd;
    private TextView mTxtOldPsdError, mTxtNewPsdError;
    private LinearLayout mLinShowPsd;
    private Button mBtnOk;
    private ImageView mImgEye;
    private boolean isHidden = true;// 是否隐藏输入框文本
    private Shop mShop;
    private LoadingDialog mLoadingDialog;
    private boolean newPsdIsDaYuSix = true;
    private boolean oldPsdIsDaYuSix = true;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        verifyLogin();
        initView();
    }

    private void verifyLogin() {
        mShop = mCaCheModel.getShop();
        if (mShop == null) {
            openFM(new FmInfo(LoginFragment.class, null));
            onDestroy();
        }
    }


    /**
     * 初始化
     */
    private void initView() {
        mActivity.SetStatusColorFE542B();
        mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
        mEditOldPsd = (EditText) mView.findViewById(R.id.txt_password_old);
        mEditNewPsd = (EditText) mView.findViewById(R.id.txt_password_new);
        mTxtOldPsdError = (TextView) mView.findViewById(R.id.txt_prompt);
        mTxtNewPsdError = (TextView) mView.findViewById(R.id.txt_error);
        mLinShowPsd = (LinearLayout) mView.findViewById(R.id.ln_show_psd);
        mRelClearOld = (RelativeLayout) mView.findViewById(R.id.rel_clear_old);
        mRelClearNew = (RelativeLayout) mView.findViewById(R.id.rel_clear_new);
        mRelClearOld.setOnClickListener(this);
        mRelClearNew.setOnClickListener(this);
        mBtnOk = (Button) mView.findViewById(R.id.ok);
        mImgEye = (ImageView) mView.findViewById(R.id.img_show_psd);
        ((TextView)mView.findViewById(R.id.title)).setText(getString(R.string.update_password));
        mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.waitting));
        mTxtNewPsdError.setVisibility(View.GONE);
        mTxtOldPsdError.setVisibility(View.GONE);
        mLinShowPsd.setOnClickListener(this);
        mBtnOk.setOnClickListener(this);
        mRelBack.setOnClickListener(this);
        setEditFocus(mEditOldPsd);
        changeLoginBtn();
        mEditOldPsd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    mRelClearOld.setVisibility(View.VISIBLE);
                } else {
                    mRelClearOld.setVisibility(View.GONE);
                }
                oldPsdIsDaYuSix = s.length() < 6;
                changeLoginBtn();
            }
        });
        mEditNewPsd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {}
            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    mRelClearNew.setVisibility(View.VISIBLE);
                } else {
                    mRelClearNew.setVisibility(View.GONE);
                }
                newPsdIsDaYuSix = s.length() < 6;
                changeLoginBtn();
            }
        });
    }

    private void changeLoginBtn() {
        if (!newPsdIsDaYuSix && !oldPsdIsDaYuSix) {
            mBtnOk.setBackgroundResource(R.drawable.btn_bg);
            mBtnOk.setEnabled(true);
        } else {
            mBtnOk.setBackgroundResource(R.drawable.btn_bg_no_click2);
            mBtnOk.setEnabled(false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mEditOldPsd.setText("");
        mEditNewPsd.setText("");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mView = inflater.inflate(R.layout.fragment_update_password, container, false);
    }

    private void clickOk() {
        String oldPsd = mEditOldPsd.getText().toString();
        String newPsd = mEditNewPsd.getText().toString();
        if (oldPsd.length() < 6) {
            mTxtOldPsdError.setVisibility(View.VISIBLE);
            setEditFocus(mEditOldPsd);
            return;
        }
        if (newPsd.length() < 6) {
            mTxtNewPsdError.setVisibility(View.VISIBLE);
            setEditFocus(mEditNewPsd);
            return;
        }
        if(!NetWorkCenterUtils.isNetworkConnected(getActivity())){
            showToast(getString(R.string.please_connect));
            return;
        }
        if(oldPsd.equals(newPsd)){
            showToast(getString(R.string.old_new_dot));
            return;
        }
        mLoadingDialog.show();
        ReqUpdatePassword reqUpdatePassword = new ReqUpdatePassword();
        reqUpdatePassword.setNewPassword(MD5Utils.md5Password(mShop.getUserName(), newPsd));
        reqUpdatePassword.setOldPassword(MD5Utils.md5Password(mShop.getUserName(), oldPsd));
        reqUpdatePassword.setuId(mShop.getuId());
        mTxtNewPsdError.setVisibility(View.GONE);
        mTxtOldPsdError.setVisibility(View.GONE);
        mHttpController.updatePassword(reqUpdatePassword, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
                String json = new String(arg2);
                Gson gson = new Gson();
                Result result = null;
                try {
                    result = gson.fromJson(json, Result.class);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast(getString(R.string.req_error));
                    return;
                }
                if (result != null) {
                    if (result.code == 1) {
                        showToast(getString(R.string.update_success));
                        onBack();
//                        openFM(new FmInfo(UserAcountFragment.class, null));
                    } else if (result.code == 2) {
                        mTxtOldPsdError.setVisibility(View.VISIBLE);
                        setEditFocus(mEditOldPsd);
                    } else {
                        showToast(getString(R.string.update_error));
                    }
                } else {
                    showToast(getString(R.string.update_error));
                }
                mLoadingDialog.dismiss();
            }
            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                showToast(getString(R.string.net_error_try));
                mLoadingDialog.dismiss();
            }
        });
    }

    private void setEditFocus(final EditText edit){
        edit.setFocusable(true);
        edit.setFocusableInTouchMode(true);
        edit.requestFocus();
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputManager =(InputMethodManager)edit.getContext().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(edit, 0);
            }
        },998);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ln_show_psd:
                showPsdOrHidePsd();
                break;
            case R.id.ok:
                clickOk();
                break;
            case R.id.back:
                onBack();
                break;
            case R.id.rel_clear_new:
                mEditNewPsd.setText("");
                break;
            case R.id.rel_clear_old:
                mEditOldPsd.setText("");
                break;
            default:
                break;
        }
    }

    /**
     * 是否显示文本框的内容
     */
    private void showPsdOrHidePsd() {
        if (isHidden) {
            mEditNewPsd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            mImgEye.setBackgroundResource(R.drawable.eye_yes);
        } else {
            mEditNewPsd.setTransformationMethod(PasswordTransformationMethod.getInstance());
            mImgEye.setBackgroundResource(R.drawable.eye_no);
        }
        isHidden = !isHidden;
        mEditNewPsd.postInvalidate();
        // 切换后将EditText光标置于末尾
        CharSequence charSequence = mEditNewPsd.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }
}
